package redis

import (
	"encoding/json"
	"gitee.com/ha666/golibs"
	"github.com/garyburd/redigo/redis"
)

//
func (c *RedisClient) Lpush(key string, value interface{}) error {
	data, err := json.Marshal(value)
	if err != nil {
		return err
	}
	_, err = c.do("LPUSH", key, data)
	return err
}

func (c *RedisClient) LpushByJsonString(key string, value interface{}) error {
	_, err :=c.do("LPUSH", key, golibs.ToJson(value))
	return err
}

func (c *RedisClient) Lpushs(key string, value ...interface{}) error {
	data, err := json.Marshal(value)
	if err != nil {
		return err
	}
	_, err = c.do("LPUSH", key, data)
	return err
}

func (c *RedisClient) LpushsByJsonString(key string, value ... interface{}) error {
	_, err :=c.do("LPUSH", key, golibs.ToJson(value))
	return err
}

func (c *RedisClient) Lranges(key string) (interface{},error ){
	return c.do("LRANGE", key)
}

func (c *RedisClient) LrangesByLen(key string,length int) ([]interface{},error ){
	//return c.do("LRANGE", key,0,len-1)
	buffer, err := redis.ByteSlices(c.do("LRANGE", key,0,length-1))
	if err != nil {
		return nil,err
	}
	if len(buffer) > 0 {   //todo    使用messagepack试试，2019-9-5
		value:=make([]interface{},len(buffer))
		for i,b:=range buffer {
			err = json.Unmarshal(b, &value[i])
			if err != nil {
				return nil,err
			}
		}
		return  value,err
	}
	return nil,err
}

func (c *RedisClient) LrangesBufferByLen(key string,length int) ([][]byte,error ){
	//return c.do("LRANGE", key,0,len-1)
	buffer, err := redis.ByteSlices(c.do("LRANGE", key,0,length-1))
	if err != nil {
		return nil,err
	}
	return buffer,err
}

func (c *RedisClient) Latest(key string) (interface{},error ){
	return c.do("LINDEX", key,0)
}
func (c *RedisClient) Expire(key string,sec int) (interface{},error ){
	return c.do("EXPIRE", key,sec)
}
func (c *RedisClient) ExpireAt(key string,unixtime int64) (interface{},error ){
	return c.do("EXPIREAT", key,unixtime)
}
